<!-- 加速终端 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <div class="top topSubmitBtn">
        <el-button class="btn" type="primary" @click="addTerminal()">添加终端</el-button>
      </div>
      <div>
        <el-table stripe :data="tableData" style="width: 100%; margin: 15px 0">
          <el-table-column type="index" width="80" label="序号"></el-table-column>
          <el-table-column prop="Department" label="从属部门" show-overflow-tooltip></el-table-column>
          <el-table-column prop="Name" show-overflow-tooltip label="终端名称"></el-table-column>
          <el-table-column prop="UserID" show-overflow-tooltip label="认证用户"></el-table-column>
          <el-table-column prop="Mobile" show-overflow-tooltip width="160" label="手机号码"></el-table-column>
          <el-table-column show-overflow-tooltip label="开通版本" width="450">
            <template slot-scope="scope">
              {{ formatRightAI(scope.row.RightAI) }}
            </template>
          </el-table-column>
          <el-table-column prop="KnowledgeRole" show-overflow-tooltip label="所属角色"></el-table-column>
          <el-table-column label="操作" width="180px" fixed="right">
            <template slot-scope="scope">
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-row>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape=false :title="title" :visible.sync="dialogVisible"
      v-el-drag-dialog width="calc(48% + 2px)">
      <el-form label-width="120px" :model="RegEmployeeForm" :rules="rules" ref="RegEmployeeForm">
        <!--顶部分割线 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-row class="rule-container">
          <div class="rule-content">
            <el-col :span="24">
              <el-form-item label='终端名称:' prop="Name">
                <el-input v-model.trim="RegEmployeeForm.Name" :disabled="title === '修改终端'" maxlength="16"
                  placeholder="请输入终端名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label='从属部门:' class="cascader" prop="Department">
                <el-cascader ref="cascaderAddr" style="width:100%;" v-model="RegEmployeeForm.Department"
                  placeholder="请选择部门" :popper-class="color === 'night' ? 'nightClass' : ''" clearable
                  :show-all-levels="false" :options="options"
                  :props="{ expandTrigger: 'hover', label: 'DepartmentName', value: 'DepartmentName', checkStrictly: true, ID: 'ID' }"
                  @visible-change="elCascaderOnlick" @expand-change="elCascaderOnlick"
                  @change="handleChange">
                </el-cascader>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label='认证用户:' prop="UserID">
                <el-input v-model.trim="RegEmployeeForm.UserID" oninput="value=value.replace(/[^0-9a-zA-z@_\-]/g,'')"
                  maxlength="24" placeholder="请输入认证用户，作为登录帐号"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label='认证密码:' prop="Pwd">
                <el-input v-model.trim="RegEmployeeForm.Pwd" maxlength="16" placeholder="请输入认证密码，作为登录密码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label='手机号码:' prop="Mobile">
                <el-input v-model.trim="RegEmployeeForm.Mobile" oninput="value=value.replace(/[^0-9]/g,'')" maxlength="11"
                  placeholder="请输入手机号码"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="开通版本:" prop="RightAI">
                <el-select v-model="RegEmployeeForm.RightAI" style="width:100%" multiple clearable
                  @change="handleSelectChange" :popper-class="color === 'night' ? 'nightClass' : ''">
                  <el-option label="全部" :value="0"></el-option>
                  <el-option v-for="(item, index) in modelList" :key="index" :label="item.name"
                    :value="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="所属角色:" prop="KnowledgeRole">
                <el-select v-model="RegEmployeeForm.KnowledgeRole" style="width:100%" clearable
                  :popper-class="color === 'night' ? 'nightClass' : ''">
                  <el-option v-for="(item, index) in RoleList" :key="index" :label="item.Role"
                    :value="item.Role"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </div>
        </el-row>
      </el-form>
      <!--   分割线与dialog-footer的间距 -->
      <el-divider class="lineToFooter"></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit()">确 定</el-button>
        <el-button type="info" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { connrequest } from "@/api/firstPage"
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { treeing, getTreeData } from "@/utils/index.js";
export default {
  directives: { elDragDialog },
  data() {
    return {
      color: '',
      title: '',
      dialogVisible: false,
      RegEmployeeForm: {
        Department: null, // 或者根据需要初始化为其他默认值
        RightAI: null
      },
      oldUserID: '',
      options: [],
      tableData: [],
      terminalName: [],
      terminalUserID: [],
      modelList: [],
      RoleList: [],
      prevSelected: [], // 用于存储上一次的选中值
      DID: '',
      rules: {
        Name: [
          { required: true, message: '请输入终端名称', trigger: 'blur' }
        ],
        Department: [
          { required: true, message: '请选择从属部门', trigger: 'change' }
        ],
        Mobile: [
          {
            validator: function (rule, value, callback) {
              if (/^1\d{10}$/.test(value) == false && value) {
                callback(new Error("手机号格式错误"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ],
        UserID: [
          { required: true, message: '请输入认证用户' }
        ],
        Pwd: [
          { required: true, message: '请输入认证密码' },
          { min: 4, max: 16, message: '长度在 4 到 16 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    // 所有选项的 id 列表（不包含 "全部"）
    allValues() {
      return this.modelList.map(item => item.id);
    },
    // 是否全选（不依赖 "全部" 的存在）
    isAllSelected() {
      return this.allValues.every(val => this.RegEmployeeForm.RightAI.includes(val));
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.GetDepartment()
    this.GetEmployee()
    this.GetAllAiInfo()
    this.GetEmployeeRole()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.color = localStorage.getItem('isNightMode') || 'night'
  },
  methods: {
    // 获取所有角色
    async GetEmployeeRole() {
      const res = await connrequest('GetEmployeeRole')
      this.RoleList = res.Data
    },
    // 获取所有AI模型
    async GetAllAiInfo() {
      const res = await connrequest('GetAllAiInfo')
      this.modelList = res.Data

    },
    // 获取所有部门
    async GetDepartment() {
      const res = await connrequest('GetDepartment')
      this.options = getTreeData(treeing(res.Data))
      if (this.options.length > 0) {
        // 如果是单选，可以直接设置第一个选项的值
        this.RegEmployeeForm.Department = this.options[0].DepartmentName;
      }
      this.GetEmployee()
    },
    // 获取终端列表并更新相关数据
    async GetEmployee() {
      const res = await connrequest('GetEmployee');
      const data = res.Data || [];
      // 提取终端名称、用户ID和准入模式
      this.terminalName = data.map(item => item.Name);
      this.terminalUserID = data.map(item => item.UserID);
      this.tableData = data;
    },
    // 添加终端，初始化表单并显示弹窗
    addTerminal() {
      this.title = '添加终端';
      this.resetForm({ RightAI: [this.modelList?.[0].id], Department: this.RegEmployeeForm.Department });
      this.dialogVisible = true;
    },
    // 编辑终端，加载数据并显示弹窗
    handleEdit(row) {
      this.title = '修改终端';
      this.oldUserID = row.UserID;
      this.resetForm({
        ...row,
        RightAI: this.echoFromCombinedValue(row.RightAI)
      });
      this.dialogVisible = true;
    },
    // 删除终端，确认后执行删除操作
    async handleDelete(row) {
      try {
        await this.$confirm('此操作将永久删除该终端, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        const res = await connrequest('DelEmployee', { Data: { ...row } });
        if (res.Status.StatusCode === 0) {
          this.$message.success('删除成功!');
          this.GetEmployee();
        }
      } catch {
        this.$message.info('已取消删除');
      }
    },
    // 处理级联选择器变化，更新DID
    handleChange(arr, node) {
      const checkedNode = this.$refs['cascaderAddr'].getCheckedNodes()[0];
      this.DID = checkedNode?.data.ID;
    },
    // 重置表单并清除验证状态
    resetForm(formData) {
      this.RegEmployeeForm = formData;
      this.$nextTick(() => {
        this.$refs['RegEmployeeForm'].clearValidate();
      });
    },
    handleSelectChange(selected) {
      const allOptions = this.modelList.map(item => item.id);
      const wasAllSelected = this.prevSelected.includes(0);
      const isAllSelected = selected.includes(0);

      if (isAllSelected && !wasAllSelected) {
        // 选择“全部”，全选
        this.RegEmployeeForm.RightAI = [0, ...allOptions];
      } else if (!isAllSelected && wasAllSelected) {
        // 取消“全部”，清空
        this.RegEmployeeForm.RightAI = [];
      } else {
        const filteredSelected = selected.filter(val => val !== 0);
        if (allOptions.every(option => filteredSelected.includes(option))) {
          // 所有选项选中，添加“全部”
          this.RegEmployeeForm.RightAI = [0, ...allOptions];
        } else {
          // 更新为用户选择的值
          this.RegEmployeeForm.RightAI = filteredSelected;
        }
      }
      this.prevSelected = [...this.RegEmployeeForm.RightAI];
    },
    // 将 RightAI 合成值转换为版本名称字符串
    formatRightAI(combinedValue) {
      if (!combinedValue) return '-';

      const allOptions = this.modelList.map(item => item.id);
      const selectedIds = allOptions.filter(id => (combinedValue & id) === id);

      // 全选时显示“全部”
      if (allOptions.every(option => selectedIds.includes(option))) {
        return '全部版本';
      }

      // 映射为名称并用逗号连接
      return this.modelList
        .filter(item => selectedIds.includes(item.id))
        .map(item => item.name)
        .join(', ') || '-';
    },
    echoFromCombinedValue(combinedValue) {
      const allOptions = this.modelList.map(item => item.id);
      const selectedValues = allOptions.filter(id => (combinedValue & id) === id);

      // 检查是否全选
      if (allOptions.every(option => selectedValues.includes(option))) {
        this.RegEmployeeForm.RightAI = [0, ...allOptions];
      } else {
        this.RegEmployeeForm.RightAI = [...selectedValues];
      }

      this.prevSelected = [...this.RegEmployeeForm.RightAI];
      return this.prevSelected;
    },
    // 计算合成值的函数
    calculateCombinedValue(selected) {
      // 过滤掉 0
      const filteredValues = selected.filter(val => val !== 0);
      // 如果数组为空，返回 0 或其他默认值
      if (filteredValues.length === 0) return 0;
      // 使用 reduce 进行按位或运算
      return filteredValues.reduce((acc, curr) => acc | curr);
    },
    // 提交表单并处理添加或修改终端的逻辑
    async submit() {
      const valid = await this.validateForm();
      if (!valid) return;
      const isAdd = this.title === '添加终端';
      const action = isAdd ? 'AddEmployee' : 'ModifyEmployee';

      // 检查终端名称和用户ID是否重复（仅限添加）
      if (isAdd && this.isNameOrUserIDExists()) return;
      // 检查用户ID是否变更且重复（仅限修改）
      if (!isAdd && this.isUserIDChangedAndExists()) return;

      // 规范化部门字段
      this.normalizeDepartment();

      // 构建请求数据
      const data = this.buildRequestData(isAdd);

      // 发送请求并处理响应
      const res = await connrequest(action, data);
      if (res.Status.StatusCode === 0) {
        this.$message.success(`${isAdd ? '添加' : '修改'}终端成功`);
        this.GetEmployee();
        this.dialogVisible = false;
      }
    },
    // 验证表单的有效性
    async validateForm() {
      return new Promise(resolve => {
        this.$refs['RegEmployeeForm'].validate(valid => resolve(valid));
      });
    },
    // 检查终端名称或用户ID是否已存在（用于添加操作）
    isNameOrUserIDExists() {
      const { Name, UserID } = this.RegEmployeeForm;
      if (this.terminalName.includes(Name)) {
        this.$message.error('该终端名称已经存在');
        return true;
      }
      if (this.terminalUserID.includes(UserID)) {
        this.$message.error('该认证用户已经存在');
        return true;
      }
      return false;
    },
    // 检查用户ID是否变更且已存在（用于修改操作）
    isUserIDChangedAndExists() {
      const { UserID } = this.RegEmployeeForm;
      if (UserID !== this.oldUserID && this.terminalUserID.includes(UserID)) {
        this.$message.error('该认证用户已经存在');
        return true;
      }
      return false;
    },
    // 规范化部门字段（数组取最后一个值）
    normalizeDepartment() {
      const { Department } = this.RegEmployeeForm;
      if (Array.isArray(Department)) {
        this.RegEmployeeForm.Department = Department[Department.length - 1];
      }
    },
    // 构建请求数据（根据操作类型添加额外字段）
    buildRequestData(isAdd) {
      const data = { Data: { ...this.RegEmployeeForm } };
      data.Data.RightAI = this.calculateCombinedValue(this.RegEmployeeForm.RightAI);
      if (isAdd) {
        data.Data.DID = this.DID;
      }
      return data;
    },
    elCascaderOnlick() {
      let that = this;
      setTimeout(function () {
        document.querySelectorAll(".el-cascader-node__label").forEach((el) => {
          el.onclick = function () {
            this.previousElementSibling.click();
            that.$refs.cascaderAddr.dropDownVisible = false;
          };
        });
      }, 100);
    }
  }
}
</script>
<style scoped lang='scss'>
.top {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.nightClass {
  .el-tag.el-tag--info {
    background-color: #2a2d3c !important;
    border-color: #2a2d3c !important;
  }

}
</style>
<style>
.el-cascader-panel .el-radio {
  display: none;
}

.el-divider {
  z-index: 111;
}
</style>
